package com.xxl.vueadmin.security;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.xxl.vueadmin.entity.SysUser;
import com.xxl.vueadmin.service.ISysUserService;
import com.xxl.vueadmin.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @version 1.0
 * @Author: 许啸林 jwt鉴权过滤器
 * @Date: 2021/7/30 19:03
 */
public class JwtAuthenticationFilter extends BasicAuthenticationFilter {

    @Autowired
    JwtUtils jwtUtils;

    @Autowired
    ISysUserService sysUserService;

    @Resource
    UserDetailServiceImpl userDetailsService;

    public JwtAuthenticationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        String token = request.getHeader(jwtUtils.getHeader());
        /**
         * 如果token 为空,则跳过该过滤器,后续过滤器判断是否为白名单请求,是则放行
         */
        if(StringUtils.isBlank(token) || token == null) {
            chain.doFilter(request, response);
            return;
        }
        Claims claims = jwtUtils.getClaims(token);
        if(claims == null) {
            throw new JwtException("令牌异常");
        }
        if(jwtUtils.checkExpired(claims)) {
            throw new JwtException("登录令牌过期,请重新登录");
        }
        String username = claims.getSubject();
        SysUser sysUser = sysUserService.getBayUserName(username);
        List<GrantedAuthority> grantedAuthorities = userDetailsService.generanteGrantList(sysUser.getId());
        UsernamePasswordAuthenticationToken userToken = new UsernamePasswordAuthenticationToken(username, null, grantedAuthorities);
        SecurityContextHolder.getContext().setAuthentication(userToken);
        chain.doFilter(request, response);
    }
}
